$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';

$(document).ready(function () {
    var $jqGrid = $("#jqGrid");
    RFQ.jqGrid("#jqGrid").init({
        url: ctx+'/rfqRequest/queryRfqQuotationList',
		postData:{rfqMethod: $('#myTab .active a').data('method')},
        colModel: [
				{
					label: '询单序号',
					name: 'id',
					index: 'id',
					width: 80,
					key: true,
					hidden:true
				},
                {
                    label: '供应商',
                    name: 'supplierId',
                    hidden:true
                },
				{
					label: '询价单号',
					name: 'unifiedRfqNum',
					index: 'UNIFIED_RFQ_NUM',
					align:'center',
					hidden:true,
					width: 80,
					formatter:selectFormatter
				},
                {
                label: '询价单号',
                name: 'ouRfqNum',
                index: 'OU_RFQ_NUM',
                align:'center',
                width: 80,
                formatter:selectFormatter
                },
				{
					label: '询单标题',
					name: 'title',
					index: 'TITLE',
					align:'center',
					width: 80
				},
				{
					label: '采购商',
					name: 'ouName',
					index: 'OU_NAME',
					align:'center',
					width: 80
				},
				{
					label: '发布人',
					name: 'issueUsername',
					index: 'ISSUE_USERNAME',
					align:'center',
					width: 60
				},
				{
					label: '发布日期',
					name: 'issueDate',
					index: 'ISSUE_DATE',
					align:'center',
					width: 80
				},
				{
					label: '报价起止时间',
					name: 'startDate',
					index: 'START_DATE',
					align:'center',
					width: 90,
					formatter:startEndTimeFormatter
				},
				{
					label: '状态',
					name: 'status',
					index: 'TYPE',
					align:'center',
					width: 60,
					formatter:formatRfqQuotationType
				},
			   {
				    label: '寻单类型',
				    name: 'rfqMethod',
				    index: 'rfqMethod',
				    width: 80,
				    key: true,
				    hidden:true
			     },
				{
					width: 80,
					label: '操作',
					name: 'id',
					index: 'id',
					sortable:false,
					formatter: actFormatter
				}
        ],
		sortname: 'ISSUE_DATE',
        sortorder: 'desc',
        pager: "#jqGridPager",
		rowNum: 20,//每页显示记录数
		rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
        loadComplete:function () {
            var $activeTab = $('#myTab .active a');
            //表单重置
            var $activeContent = $($activeTab.attr('href'));
            $activeContent.find('.searchFormTab')[0].reset();
            $.placeholder();
            //状态重置
            var $lis = $activeContent.find('.navbar-nav li');
            $lis.removeClass('active');
            //默认为全部状态激活
            $lis.eq(0).addClass('active');
            var rfqMethod = $activeTab.data('method') || '';
            if (rfqMethod == "RAQ" || rfqMethod == 'DAC') {
                $.get(ctx + '/rfqRequest/fingByRfqSupplierType', {rfqMethod: rfqMethod}, function (data) {
                    var staticDatas = {};
                    $.each(data, function (i, d) {
                        staticDatas[d.type] = d.count;
                    });
                    $lis.each(function () {
                        var $a = $(this).find('a');
                        $a.find('strong').text('(' + (staticDatas[$a.data('type')] || 0) + ')');
                    });
                }, 'json');
            }
        }

    });

	function actFormatter(cellvalue, options, rawObject) {
		var rtype = rawObject.status;
		var rmethod=rawObject.rfqMethod;
        //报价详情
		var detailBtn = '<span class="ml5"><a class="btn btn-sm btn-info js-check re" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'"  data-action="rfqRequestHistory(\'' + rawObject.id + '\',\'' + rawObject.supplierId + '\',\'' +rtype+ '\',\'' +rmethod+ '\')" href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>';
		if(rtype=="0"||rtype=="8"){ //查看询单详情
			detailBtn = '<span class="ml5"><a class="btn btn-sm btn-info js-check re" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'"  data-action="rfqRequestDetail(\'' + rawObject.id + '\',\'' + rawObject.supplierId+ '\',\''+rawObject.rfqMethod+ '\')"  href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>';
		}
		if(rtype=="2"&&'RAQ'==rmethod){ //报价页面
			var detailBtn = '<span class="ml5"><a class="btn btn-sm btn-info js-check re" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'"  data-action="rfqRequestHistory(\'' + rawObject.id + '\',\'' + rawObject.supplierId + '\',\'' +rtype+ '\',\'' +rmethod+ '\')" href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>';
		}
		if(rtype=="1"&&'RAQ'==rmethod){ //报价页面
			detailBtn = '<span class="ml5"><a class="btn btn-sm btn-warning js-check re" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'"  data-action="rfqRequestQuotation(\'' + rawObject.id +  '\',\'' + rawObject.supplierId+ '\',\''+ rmethod+'\')"  href="javascript:;"><i class="icon icon-yen"></i> 报价</a></span>';
		}else if(rtype=="1"&&'PSCS'==rmethod){
			detailBtn = '<span class="ml5"><a class="btn btn-sm btn-warning js-check re" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'"  data-action="rfqRequestQuotation(\'' + rawObject.id + '\',\''+rawObject.supplierId+'\',\'' + rmethod+ '\')"  href="javascript:;"><i class="icon icon-yen"></i> 报价</a></span>';
		}
		if(rtype=="1"&&'DAC'==rmethod){
			detailBtn = '<span class="ml5"><a class="btn btn-sm btn-warning js-check re" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'"  data-action="quotationBidding(\'' + rawObject.id + '\')"   target="myquotation"><i class="icon icon-yen"></i>竞价</a></span>';
		}
		if(rtype=="2"&&'DAC'==rmethod){
			detailBtn = '<span class="ml5"><a class="btn btn-sm btn-info js-check re" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'"  data-action="quotationBid(\'' + rawObject.id + '\',\'' +rtype+ '\')"  target="myquotation"><i class="icon icon-zoom-in"></i> 查看</a></span>';
		}
		if(rtype=="2"&&'PSCS'==rmethod){ //报价页面
			var detailBtn = '<span class="ml5"><a class="btn btn-sm btn-info js-check re" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'"  data-action="rfqRequestHistory(\'' + rawObject.id + '\',\'' + rawObject.supplierId + '\',\'' +rtype+ '\',\'' +rmethod+ '\')" href="javascript:;"><i class="icon icon-zoom-in"></i> 查看</a></span>';
		}
		if(rtype=="1"&&'PSCS'==rmethod){ //报价页面
			detailBtn = '<span class="ml5"><a class="btn btn-sm btn-warning js-check re" data-supplierid="'+rawObject.supplierId+'" data-type="'+rtype+'"  data-action="rfqRequestQuotation(\'' + rawObject.id + '\',\'' + rawObject.supplierId+ '\')"  href="javascript:;"><i class="icon icon-yen"></i> 报价</a></span>';
		}
		return detailBtn;
	};

	//状态校验
	$jqGrid.on('click','.js-check', function () {
		var $this = $(this);
		var id = $this.data('supplierid');
		var type = $this.data('type');
		var action =  $this.data('action');
        $.post(ctx + '/rfqQuotation/checkState', {id: id, status: type}, function (msg) {
            if (msg.rspcod != 200) {
                RFQ.error(msg.rspmsg || '网络异常！');
                window.location.reload();
            }else{
            eval(action);
            }
        });
	});

	var $myTab = $('#myTab');
	//搜索按钮点击
	$('button.btnSearch').on('click',function(){
		jqGridReload();
	});

	//标签页切换
	$myTab.find('[data-toggle]').on('shown.zui.tab', function(e) {
		var $activeTab = $(e.target);
		//表单重置
		var $activeContent = $($activeTab.attr('href'));
		$activeContent.find('.searchFormTab')[0].reset();
        $.placeholder();
		//状态重置
		var $lis = $activeContent.find('.navbar-nav li');
		$lis.removeClass('active');
		//默认为全部状态激活
		$lis.eq(0).addClass('active');
		//数据重新加载
		jqGridReload2();
		var rfqMethod = $activeTab.data('method')||'';
		if(rfqMethod=="RAQ"||rfqMethod=='DAC'){
			$.get( ctx+'/rfqRequest/fingByRfqSupplierType',{rfqMethod:rfqMethod},function(data){
				var staticDatas = {};
				$.each(data,function(i,d){
					staticDatas[d.type] = d.count;
				});
				$lis.each(function(){
					var $a = $(this).find('a');
					$a.find('strong').text('('+(staticDatas[$a.data('type')]||0)+')');
				});
			},'json');
		}
	});

	//状态页切换
	$('div.tab-content').on('click','.navbar-nav a',function(){
		var $this = $(this);
		$this.parent().addClass('active').siblings().removeClass('active');
		jqGridReload();
	});

	function jqGridReload(){
		//选择的模式
		var $activeTab = $myTab.find('.active a');
		var rfqMethod = $activeTab.data('method')||'';
		//选择的状态以及表单
		var $activeContent = $($activeTab.attr('href'));
		var type = $activeContent.find('.navbar-nav .active a').attr('data-type')||'';
		//表单id
		var formId= $activeContent.find('.searchFormTab')[0].id;
		var params = {rfqMethod:rfqMethod,status:type};
		var postData = $.extend(form2Json(formId),params);
		$jqGrid.jqGrid('setGridParam',{postData: postData,page: 1}).trigger("reloadGrid");
	}

//切换标签栏时用的,切换时需要把所有搜索条件置空
    function jqGridReload2(params){
        //选择的模式
        var $activeTab = $myTab.find('.active a');
        var rfqMethod = $activeTab.data('method')||'';
        //选择的状态以及表单
        var $activeContent = $($activeTab.attr('href'));
        var type = $activeContent.find('.navbar-nav .active a').attr('data-type')||'';
        //表单id
        var formId= $activeContent.find('.searchFormTab')[0].id;
        var params = {rfqMethod:rfqMethod,status:type};
        var postData = $.extend(form2Json(formId),params);
        postData.unifiedRfqNum=null;
        postData.title=null;
        postData.ouName=null;
        postData.issueStartDate=null;
        postData.issueEndDate=null;
        postData.startDateStart=null;
        postData.startDateEnd=null;
        postData.quotationStartDate=null;
        postData.quotationEndDate=null;
        $jqGrid.jqGrid('setGridParam', {
            postData: postData,
            page: 1
        }).trigger("reloadGrid");
    }
});
/**
 * 未开始
 */
function rfqRequestDetail(id,supplierId,rfqMethod) {
	if('RAQ'==rfqMethod){
		location.href = ctx+"/rfqRequest/rfqRequestDetail?id=" + id;
	}else if('DAC'==rfqMethod){
		window.sessionStorage.designateResult_tax="NoStart";
		location.href = ctx+"/dacReverseAuction/reverseAuctionDetail?id=" + id;
	}

}
/**
 * 报价明细
 */
function rfqRequestHistory (id,supplierId,rtype,rmethod ){
	if('RAQ'==rmethod || 'PSCS'==rmethod){
		if('2' == rtype ){
			//供应商报价时对报价人员验证
			$.ajax({
				url:ctx+"/rfqQuotationLock/editRfqQuotationLock",
				data:{requestId:id},
				type:'POST',
				async: false,
				success:function(data){
					if(data.rspcod != 200){
						RFQ.error(data.rspmsg);
						return;
					}else{
						location.href = ctx+"/rfqQuotationHisotry/getRfqQuotationHistory?requestId=" + id+"&supplierId="+supplierId;
					}
				}
			});
		}else {
			location.href = ctx+"/rfqQuotationHisotry/getRfqQuotationHistory?requestId=" + id+"&supplierId="+supplierId;
		}
	}else if('DAC'==rmethod){
		if('3'==rtype){//结果待发布
			window.sessionStorage.type='3';
			//获取采购方状态；
			$.ajax({
				url:ctx+"/designateContract/quateSupplier",
				data:{requestId:id},
				success:function(data){
					var data = eval(data);
					//console.log(data);
					//alert (data.supplierId == supplierId);
					if (data.isWad == 1) {//已补填明细
						location.href = ctx+"/dacQuotationTotal/tryBidding?requestId="+id+"&type="+rtype;
					} else {//未补填明细
						if (data.supplierId == supplierId) {//已中标
							location.href = ctx+"/win/"+id+"?type="+rtype;
						}else {//未中标
							location.href = ctx+"/weizhongbiao/getRfqQuotationHistory?requestId="+id+"&type="+rtype;
						}
					}
				}
			});
		}
		if('4'==rtype||'7'==rtype){//已放弃//已作废
			location.href = ctx+"/dacQuotationTotal/tryBidding?requestId="+id+"&type="+rtype;
		}
		if('5'==rtype){//已中标
			location.href = ctx+"/win/"+id;
		}
		if('6'==rtype){//未中标
			location.href = ctx+"/weizhongbiao/getRfqQuotationHistory?requestId="+id;
		}
	}

}
/**
 * 报价
 */
function rfqRequestQuotation(id,supplierId,rmethod) {
	//供应商报价时对报价人员验证
	debugger;
	$.ajax({
		url:ctx+"/rfqQuotationLock/editRfqQuotationLock",
		data:{requestId:id},
		type:'POST',
		async: false,
		success:function(data){
			if(data.rspcod != 200){
				RFQ.error(data.rspmsg);
				return;
			}else{
				debugger;
				if(rmethod == 'RAQ'){
					debugger;
					location.href = ctx+"/rfqQuotation/getRfqQuotation?requestId=" + id+"&supplierId="+supplierId+"&quotationType=quotation&rmethod="+rmethod;
				}else if(rmethod == 'PSCS'){
					location.href = ctx+"/rfqQuotation/getRfqQuotation?requestId=" + id+"&supplierId="+supplierId+"&quotationType=quotation&rmethod="+rmethod;
				}
			}

		}
	});

}

function quotationBidding(id) {
	$.ajax({
		url:ctx+"/rfqQuotationLock/editRfqQuotationLock",
		data:{requestId:id},
		async: false,
		type:'POST',
		success:function(data){
			if(data.rspcod != 200){
				RFQ.error("对不起，竞价单已被锁定！");
				return;
			}else{
				window.sessionStorage.designateResult_tax="NoStart";
				location.href = ctx+"/dacReverseAuction/reverseAuctionDetail?id=" + id;
			}
		}
	});

}
function quotationBid(id,rtype) {
    alert(rtype);
	$.ajax({
		url:ctx+"/rfqQuotationLock/editRfqQuotationLock",
		data:{requestId:id},
		type:'POST',
		async: false,
		success:function(data){
			if(data.rspcod != 200){
				RFQ.error("对不起，竞价单已被锁定！");
				return;
			}else{
				$.ajax({
					url:ctx+"/rfqRequest/queryRules",
					data:{requestId:id},
					type:'POST',
					async: false,
					success:function(data){
						var rule=data.rules;
						if('1'==rule){
							location.href = ctx+"/dacQuotationTotal/init?requestId="+id+"&type="+rtype;
						}else if('0'==rule){
							window.sessionStorage.type="";
							location.href = ctx+"/dacQuotationSingle/init?requestId="+id+"&type="+rtype;
						}else{
							$.zui.messager.show('链接失败！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
						}
					}
				});
			}
		}
	});

}
/**
 * 起止时间格式化
 */
function startEndTimeFormatter(cellvalue, options, rawObject) {
	var endDate = rawObject.quotationEndDate;
	return cellvalue +'~\n'+ endDate;
}


/**
 * 询单编号链接跳转
 */
function selectFormatter(cellvalue, options, rawObject) {
	var id = rawObject.id;
	if('RAQ'==rawObject.rfqMethod){
		return "<a class='blue' target='_blank' href='"+ctx+"/rfqRequest/rfqRequestDetail?id="+id+"' >"+cellvalue+"</a>";
	}else if('DAC'==rawObject.rfqMethod){
		return "<a class='blue' target='_blank'  href='"+ctx+"/dacReverseAuction/reverseAuctionDetail?id="+id+"' >"+cellvalue+"</a>";
	}else{
		return "<a class='blue' target='_blank' href='"+ctx+"/rfqRequest/rfqRequestDetail?id="+id+"' >"+cellvalue+"</a>";
	}

}

typeList=function (data){
	$("#rfqMethod").val(data);
	if('RAQ'==data||''==data){
		$("#jqGrid").jqGrid('setLabel', 3,"询价单号");
		$("#jqGrid").jqGrid('setLabel', 4,"询价标题");
		$("#jqGrid").jqGrid('setLabel', 8,"报价起止时间");
	}else if('DAC'==data){
		$("#jqGrid").jqGrid('setLabel', 3,"竞价单号");
		$("#jqGrid").jqGrid('setLabel', 4,"竞价标题");
		$("#jqGrid").jqGrid('setLabel', 8,"竞价起止时间");
	}
};